package com.szholly.pro.watergas_server.ps.android.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.ps.android.bean.QcTaskParam;
import com.szholly.pro.watergas_server.ps.android.common.DateTime;
import com.szholly.pro.watergas_server.ps.android.common.FieldInterceptor;
import com.szholly.pro.watergas_server.ps.android.common.NonNullUtil;
import com.szholly.pro.watergas_server.ps.android.common.SecurityConfig;
import com.szholly.pro.watergas_server.ps.android.common.SqlUtils;
import com.szholly.pro.watergas_server.ps.android.common.TableRowMap;
import com.szholly.pro.watergas_server.ps.android.common.ValidUtils;
import com.szholly.pro.watergas_server.ps.android.controller.QcControl;
import com.szholly.pro.watergas_server.ps.android.controller.QcService;
import com.szholly.pro.watergas_server.ps.data.OperationTaskRow;
import com.szholly.pro.watergas_server.ps.data.OperationTaskTable;
import com.szholly.pro.watergas_server.ps.data.QcExpdataRow;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class QcTaskLabStrategy extends QcTaskStrategy {
	private QcBatchService mBatchService = QcBatchService.INSTANCE;
	private String[] MAIN_TABLE_NEED_FIELD = { QcExpdataRow.FIELD_ExpNumber, QcExpdataRow.FIELD_Monitortypecode, QcExpdataRow.FIELD_Qccompanycode, QcExpdataRow.FIELD_Qctypecode, QcExpdataRow.FIELD_Datetime, QcExpdataRow.FIELD_Samplenumber, QcExpdataRow.FIELD_ExpPhoto };

	private final static String TABLE_lAB_RELATION = "QC_EXPRELATION";
	private final static String MAIN_TABLE_NAME = "QC_EXPDATA";
	private final static String TABLE_lAB_VALUE = "QC_EXPDETAILDATA";
	private final static String TABLE_lAB_PERSON = "QC_EXPNUMBER_PERSON";
	QcService mDomainManager = QcService.get();

	public QcTaskLabStrategy(QcOperationService mOperationService) {
		super(mOperationService);
	}

	@Override
	public List<RowBase> getTaskList(QcTaskParam taskParam) throws Exception {
		String companyCode = taskParam.getCompanyCode();
		String pointCode = taskParam.getPointCode();
		List<RowBase> taskList = getTaskList(companyCode, pointCode, null);

		List<RowBase> completeTaskList = completeTaskDataDes(taskList);
		List<RowBase> batchList = mBatchService.getLabBatchList(companyCode);
		List<RowBase> resultList = new ArrayList<>();
		resultList.addAll(batchList);
		resultList.addAll(completeTaskList);
		return resultList;
	}

	// 根据站点编号或者公司编号获取运维任务
	private List<RowBase> getTaskList(String companyCode, String pointCode, String taskCode) throws Exception {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("sampleJobId", QcControl.SAMPLE.getJobId()));
		String taskSql = "select t.TASK_CODE \"id\",\n"
				+ "       case\n"
				+ "         when t.Task_Status = '0' and t.parent_task_code is not null then\n"
				+ "          '待分析  创建时间：' || to_char(t.START_TIME, 'yyyy-mm-dd hh24:mi:ss')\n"
				+ "       end \"name\",\n"
				+ "       t.TASK_DESC \"des\",\n"
				+ "       t.Task_Status \"type\",\n"
				+ "       t.parent_task_code \"parentCode\",\n"
				+ "       to_char(t.START_TIME, 'yyyy-mm-dd hh24:mi:ss') \"startTime\",\n"
				+ "       to_char(t.END_TIME, 'yyyy-mm-dd hh24:mi:ss') \"endTime\",\n"
				+ "       t.FINISH_BY \"userId\"\n"
				+ "  from OP_TASK t\n"
				+ " where 1 = 1\n"
				+ "   and t.parent_task_code is not null\n"
				+ "   and t.job_id = @sampleJobId";
		if (!StringUtils.IsNullOrSpace(companyCode)) {
			parms.add(new GlobalParameter("companyCode", companyCode));
			taskSql += "   and t.wwtp_id = @companyCode\n";
		}
		if (!StringUtils.IsNullOrSpace(taskCode)) {
			parms.add(new GlobalParameter("taskCode", taskCode));
			taskSql += "   and t.task_code = @taskCode\n";
		}
		taskSql += "order by  t.start_time desc";
		List<RowBase> rows = DataUtil.getSelectRows(taskSql, parms);
		return NonNullUtil.toList(rows);
	}

	@Override
	public RowBase addTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		JSONObject dataJSONObject = JSONObject.fromObject(data);
		String taskDes = dataJSONObject.optString("taskDes");
		String parameterCode = dataJSONObject.optString("parameterCode");
		String qcTypeCode = dataJSONObject.optString("qcTypeCode");
		String monitorTypeCode = dataJSONObject.optString("monitorTypeCode");
		String taskCode = crateTaskCode(taskParam);

		String parentCode = taskParam.getParentTaskCode();
		String userId = taskParam.getUserId();
		String companyCode = taskParam.getCompanyCode();
		ValidUtils.hasText(userId, "用户编号为空");
		OperationTaskRow row = new OperationTaskRow();
		row.setStartTime(new Date());
		row.setFinishBy(userId);
		row.setJobId(QcControl.LAB.getJobId());
		row.setTaskCode(taskCode);
		row.setTaskStatus("0");
		row.setParentTaskCode(parentCode);
		row.setWwtpId(companyCode);
		row.setTaskDesc(taskDes);
		row.setParmId(parameterCode);
		row.setStationId(monitorTypeCode);
		row.setFlowType(qcTypeCode);
		SqlUtils.insert(OperationTaskTable.TABLE_NAME, row);
		List<RowBase> contentList = getContentList(parentCode);
		for (RowBase rowBase : contentList) {
			String code = (String) rowBase.get("taskCode");
			if (taskCode.equals(code)) {
				return rowBase;
			}
		}
		throw new Exception();
	}

	@Override
	public void deleteTask(QcTaskParam taskParam) throws Exception {
		mOperationService.deleteOperationTask(taskParam);
	}

	private void executeDeleteTaskContent(String taskCode) {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String mainDeleteSql = "delete from QC_EXPDATA t\n" + " where t.operation_task_code = @taskCode";
		String relationSql = "delete from qc_exprelation t where t.exp_number in (\n"
				+ "select t1.exp_number from QC_EXPDATA t1 where t1.operation_task_code = @taskCode)";
		String valueDeleteSql = "delete from QC_EXPDETAILDATA t where t.exp_number in(\n"
				+ "select t1.exp_number from QC_EXPDATA t1 where t1.operation_task_code = @taskCode)";
		String personDeleteSql = "delete from QC_EXPNUMBER_PERSON t where t.exp_number in(\n"
				+ "select t1.exp_number from QC_EXPDATA t1 where t1.operation_task_code = @taskCode)";
		DataUtil.ExecuteUpdateSql(valueDeleteSql, parms);
		DataUtil.ExecuteUpdateSql(personDeleteSql, parms);
		DataUtil.ExecuteUpdateSql(relationSql, parms);
		DataUtil.ExecuteUpdateSql(mainDeleteSql, parms);
	}

	@Override
	public void deleteProcessedTask(QcTaskParam taskParam) throws Exception {
		String userId = taskParam.getUserId();
		String taskCode = taskParam.getTaskCode();

		SecurityConfig config = SecurityConfig.get(userId);
		ValidUtils.isTrue(config.containQcDeleteProcessedTask, "权限不够");
		try {
			DataUtil.beginTransaction();
			executeDeleteTaskContent(taskCode);
			mOperationService.deleteOperationTask(taskParam);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	@Override
	public RowBase getProcessedTaskInitData(QcTaskParam taskParam) throws Exception {
		return getInitData(taskParam);
	}

	@Override
	public RowBase getTaskInitData(QcTaskParam taskParam) throws Exception {
		return getInitData(taskParam);
	}

	private RowBase getInitData(QcTaskParam taskParam) throws Exception {
		String companyCode = taskParam.getCompanyCode();
		String batchCode = taskParam.getTaskCode();
		List<RowBase> parameterList = mParameterService.getBatchProjectList(batchCode, companyCode);
		List<RowBase> labMethodList = mBatchService.getLabMethodList(batchCode);
		List<RowBase> monitorTypeList = mBatchService.getMonitorTypeList(batchCode);
		List<RowBase> qcTypeList = mDomainManager.getLabQcTypeList();
		List<RowBase> personList = mDomainManager.getPersonList(companyCode, "0");
		Map<String, Map<String, List<String>>> sampleCodeMap = mBatchService.getSampleCodeMap(batchCode);
		List<RowBase> contentList = getContentList(batchCode);

		String dateTime = new DateTime().toString();
		String rule = QcService.getSamplePrefix(companyCode);// 命名规则
		String sampleCode1 = rule + new DateTime().toString("yyyyMMdd");
		String sampleCode2 = rule + new DateTime().toString("yyyyMMdd");

		// 质控类型默认选第一个
		qcTypeList.get(0).put("checked", true);
		RowBase resultMap = new RowBase();
		resultMap.put("parameterList", NonNullUtil.toList(parameterList));
		resultMap.put("qcTypeList", NonNullUtil.toList(qcTypeList));
		resultMap.put("personList", NonNullUtil.toList(personList));
		resultMap.put("labMethodList", NonNullUtil.toList(labMethodList));
		resultMap.put("monitorTypeList", NonNullUtil.toList(monitorTypeList));
		resultMap.put("contentList", NonNullUtil.toList(contentList));
		resultMap.put("sampleCodeMap", sampleCodeMap);

		resultMap.put("dateTime", dateTime);
		resultMap.put("sampleCode1", sampleCode1);
		resultMap.put("sampleCode2", sampleCode2);
		return resultMap;
	}

	// 获取实验数据
	private List<RowBase> getContentList(String batchCode) {
		List<GlobalParameter> parms = new ArrayList<>();
		parms.add(new GlobalParameter("batchCode", batchCode));
		parms.add(new GlobalParameter("jobId", QcControl.LAB.getJobId()));
		String taskSql = "select t.task_code \"taskCode\",\n"
				+ "       max(t.task_desc) \"taskDes\",\n"
				+ "       max(t.task_status) \"taskStatus\",\n"
				+ "       max(t.FLOW_TYPE) \"qcTypeCode\",\n"
				+ "       max(t.STATION_ID) \"monitorTypeCode\",\n"
				+ "       max(t.PARM_ID) \"parameterCode\",\n"
				+ "       max(t2.exp_rd) \"errorValue\"\n"
				+ "  from OP_TASK t\n"
				+ "  left join qc_expdata t1\n"
				+ "    on t1.operation_task_code = t.task_code\n"
				+ "  left join qc_expdetaildata t2\n"
				+ "    on t2.exp_number = t1.exp_number\n"
				+ " where t.parent_task_code = @batchCode\n"
				+ "   and t.job_id = @jobId\n"
				+ " group by t.task_code\n"
				+ " order by max(t.task_status) asc";

		List<RowBase> taskRows = DataUtil.getSelectRows(taskSql, parms);
		Map<String, RowBase> taskMap = new HashMap<>();
		for (RowBase rowBase : taskRows) {
			taskMap.put((String) rowBase.get("taskCode"), rowBase);
		}
		String labSql = "select t.exp_number \"labCode\",\n"
				+ "       max(t.samplenumber) \"sampleCode\",\n"
				+ "       max(t2.exp_methodcode) \"methodCode\",\n"
				+ "       max(t.exp_photo) \"photoUrl\",\n"
				+ "       max(t4.PERSON_NAME) \"personStr\",\n"
				+ "       max(t2.exp_mvalue) \"measureValue\",\n"
				+ "       max(t2.EXP_SSD_SVALUE) \"standardValue\",\n"
				+ "       max(t2.EXP_SSD_QS_CS) \"standardLimitValue\",\n"
				+ "       max(t2.EXP_SSD_MVALUE_CS) \"standardMeasureValue\",\n"
				+ "       max(t.operation_task_code) operation_task_code\n"
				+ "  from qc_expdata t\n"
				+ "  left join operation_task t1\n"
				+ "    on t1.task_code = t.operation_task_code\n"
				+ "  left join qc_expdetaildata t2\n"
				+ "    on t.exp_number = t2.exp_number\n"
				+ "  left join (select t.exp_number,\n"
				+ "                    wm_concat(to_char(t1.personname)) PERSON_NAME\n"
				+ "               from qc_expnumber_person t\n"
				+ "               left join qc_companypersoninfo t1\n"
				+ "                 on t.exp_personcode = t1.personcode\n"
				+ "              group by t.exp_number) t4\n"
				+ "    on t4.exp_number = t.exp_number\n"
				+ "  left join qc_exprelation t5\n"
				+ "    on t5.exp_number = t.exp_number\n"
				+ " where t1.parent_task_code = @batchCode\n"
				+ " group by t.exp_number, t5.guid\n"
				+ " order by t5.guid";
		List<RowBase> labRows = DataUtil.getSelectRows(labSql, parms);
		for (RowBase rowBase : labRows) {
			String taskCode = rowBase.getSafeString("operation_task_code");
			RowBase taskRow = taskMap.get(taskCode);
			if (taskRow != null) {
				if (taskRow.containsKey("lab1")) {
					taskRow.put("lab2", rowBase);
				} else {
					taskRow.put("lab1", rowBase);
				}
			}
			taskRow.remove("OPERATION_TASK_CODE");
		}

		for (RowBase rowBase : taskRows) {
			if (!rowBase.containsKey("lab1")) {
				rowBase.put("lab1", new HashMap<>());
			}
			if (!rowBase.containsKey("lab2")) {
				rowBase.put("lab2", new HashMap<>());
			}
		}
		return taskRows;
	}

	@Override
	public void saveTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		JSONObject json = JSONObject.fromObject(data);
		List<TableRowMap> saveList = getSaveList(json);
		makeSureSampleCodeNotEqual(saveList);
		makeSureLabCodeNotEqual(saveList);
		makeSureSampleValidByMonitorType(saveList);
		try {
			DataUtil.beginTransaction();
			SqlUtils.prepareInsert(saveList);
			preFinishChildOperationTask(json);

			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	@Override
	public void updateTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		String taskCode = taskParam.getTaskCode();
		JSONObject json = JSONObject.fromObject(data);
		List<TableRowMap> saveList = getSaveList(json);

		makeSureSampleCodeNotEqual(saveList);
		makeSureLabCodeNotEqual(saveList);
		makeSureSampleValidByMonitorType(saveList);
		try {
			// 删除原有的数据
			DataUtil.beginTransaction();
			executeDeleteTaskContent(taskCode);
			// 插入修改后的数据
			SqlUtils.prepareInsert(saveList);
			preFinishChildOperationTask(json);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	private void preFinishChildOperationTask(JSONObject data) throws Exception {
		JSONObject taskJSONObject = data.getJSONObject("taskBean");
		ValidUtils.notNull(taskJSONObject, "运维任务数据为空");
		String taskCode = taskJSONObject.optString("TASK_CODE");
		String taskDes = taskJSONObject.optString("TASK_DESC");
		String type = taskJSONObject.optString("TASK_STATUS");
		ValidUtils.hasText(taskCode, "任务编号不能为空");
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		parms.add(new GlobalParameter("desc", taskDes));
		parms.add(new GlobalParameter("type", type));
		parms.add(new GlobalParameter("endTime", new DateTime().toString()));
		String sql = "update OPERATION_TASK t set t.task_desc = @desc,t.Task_Status = @type,t.END_TIME =to_date(@endTime,'yyyy-mm-dd hh24:mi:ss') where t.TASK_CODE = @taskCode";
		DataUtil.ExecuteUpdateSql(sql, parms);
	}

	// 获取保存的数据
	private List<TableRowMap> getSaveList(JSONObject data) throws Exception {
		List<TableRowMap> saveList = new ArrayList<>();
		data = completeLabCode(data);
		JSONObject labJsonObject1 = data.optJSONObject("1");
		JSONObject labJsonObject2 = data.optJSONObject("2");

		final List<TableRowMap> mainTableList = new ArrayList<>();
		final List<TableRowMap> personTableList = new ArrayList<>();
		final List<TableRowMap> valueTableList = new ArrayList<>();

		personTableList.addAll(getPersonTableList(labJsonObject1));
		valueTableList.addAll(getValueTableList(labJsonObject1));
		mainTableList.add(getMainTableRow(labJsonObject1));

		final String qcType = labJsonObject1.optString(QcExpdataRow.FIELD_Qctypecode);
		// 第二组实验
		if (QcHelper.getLabCount(qcType) == 2) {
			personTableList.addAll(getPersonTableList(labJsonObject2));
			valueTableList.addAll(getValueTableList(labJsonObject2));
			mainTableList.add(getMainTableRow(labJsonObject2));
		}

		TableRowMap relationMap = getRelationTableRow(mainTableList);
		saveList.add(relationMap);
		saveList.addAll(mainTableList);
		saveList.addAll(personTableList);
		saveList.addAll(valueTableList);
		return saveList;
	}

	// 根据样品编号创建说实验编号
	private String createLabCode(String sampleId) {
		ValidUtils.hasText(sampleId, "样品ID为空");
		try {
			List<GlobalParameter> parms = new ArrayList<>();
			parms.add(new GlobalParameter("sampleId", sampleId));
			String sql = "select max(to_number(substr(t.exp_number, length(t.exp_number) - 2))) max_num\n"
					+ "  from QC_EXPDATA t\n"
					+ " where t.samplenumber = @sampleId";
			List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
			int maxNum = rows.get(0).getSafeInt("max_num");
			return sampleId + String.format("%03d", maxNum + 1);
		} catch (Exception e) {
			return sampleId + String.format("%03d", 1);
		}
	}

	// 完善数据，增加实验编号
	private JSONObject completeLabCode(JSONObject data) throws Exception {
		JSONObject labJsonObject1 = data.optJSONObject("1");
		JSONObject labJsonObject2 = data.optJSONObject("2");

		// 第一组实验
		ValidUtils.notNull(labJsonObject1, "数据为空");
		final String qcType = labJsonObject1.optString(QcExpdataRow.FIELD_Qctypecode);
		ValidUtils.hasText(qcType, "质控类型为空");
		String sampleCode1 = labJsonObject1.optString("SAMPLENUMBER");
		String labCode1 = createLabCode(sampleCode1);
		labJsonObject1.put(QcExpdataRow.FIELD_ExpNumber, labCode1);
		// 第二组实验
		if (QcHelper.getLabCount(qcType) == 2) {
			ValidUtils.notNull(labJsonObject2, "数据为空");
			String sampleCode2 = labJsonObject2.optString("SAMPLENUMBER");
			String labCode2 = createLabCode(sampleCode2);
			labJsonObject2.put(QcExpdataRow.FIELD_ExpNumber, labCode2);
		}
		data.put("1", labJsonObject1);

		return data;
	}

	// 获取主表
	private TableRowMap getMainTableRow(JSONObject labJsonObject) throws Exception {
		labJsonObject.remove("personList");
		labJsonObject.remove("valueList");
		TableRowMap mainTable = TableRowMap.get(labJsonObject, MAIN_TABLE_NAME);
		FieldInterceptor mainTableInterceptor = FieldInterceptor.createNotNullInterceptor(MAIN_TABLE_NEED_FIELD);
		mainTable.setFieldInterceptor(mainTableInterceptor);
		return mainTable;
	}

	// 获取人员信息数据
	private List<TableRowMap> getPersonTableList(JSONObject labObject) throws Exception {
		String labCode = labObject.optString(QcExpdataRow.FIELD_ExpNumber);
		JSONArray personArray = labObject.optJSONArray("personList");
		List<TableRowMap> personList = TableRowMap.get(personArray, TABLE_lAB_PERSON);
		for (TableRowMap bean : personList) {
			bean.put("EXP_NUMBER", labCode);
		}
		return personList;
	}

	// 获取人员数值数据
	private List<TableRowMap> getValueTableList(JSONObject labJsonObject) throws Exception {
		String labCode = labJsonObject.optString(QcExpdataRow.FIELD_ExpNumber);
		JSONArray personArray = labJsonObject.optJSONArray("valueList");
		List<TableRowMap> list = TableRowMap.get(personArray, TABLE_lAB_VALUE);
		for (TableRowMap bean : list) {
			bean.put("EXP_NUMBER", labCode);
		}
		return list;
	}

	private TableRowMap getRelationTableRow(List<TableRowMap> list) throws Exception {
		List<String> labCodeList = new ArrayList<String>();
		for (TableRowMap bean : list) {
			if (bean.getTableName().equals(MAIN_TABLE_NAME)) {
				labCodeList.add((String) bean.get(QcExpdataRow.FIELD_ExpNumber));
			}
		}
		TableRowMap relationTableRow = new TableRowMap(TABLE_lAB_RELATION);
		relationTableRow.put("EXP_NUMBER", labCodeList.get(0));
		if (labCodeList.size() >= 2) {
			relationTableRow.put("RELATEDEXP_NUMBER", labCodeList.get(1));
		}
		return relationTableRow;
	}

	private void makeSureSampleCodeNotEqual(List<TableRowMap> list) throws Exception {
		Set<String> sampleSet = new HashSet<>();
		for (TableRowMap bean : list) {
			if (bean.getTableName().equals(MAIN_TABLE_NAME)) {
				String sampleCode = (String) bean.get(QcExpdataRow.FIELD_Samplenumber);
				if (sampleSet.contains(sampleCode)) {
					throw new Exception("采样编号相同");
				}
				sampleSet.add(sampleCode);
			}
		}
	}

	private void makeSureLabCodeNotEqual(List<TableRowMap> list) throws Exception {
		Set<String> set = new HashSet<>();
		for (TableRowMap bean : list) {
			if (bean.getTableName().equals(MAIN_TABLE_NAME)) {
				String labCode = (String) bean.get(QcExpdataRow.FIELD_ExpNumber);
				if (set.contains(labCode)) {
					throw new Exception("实验编号相同");
				}
				set.add(labCode);
			}
		}
	}

	// 样品编号与监测类型不能有冲突
	private void makeSureSampleValidByMonitorType(List<TableRowMap> list) throws Exception {
		for (TableRowMap bean : list) {
			if (bean.getTableName().equals(MAIN_TABLE_NAME)) {
				String sampleCode = (String) bean.get(QcExpdataRow.FIELD_Samplenumber);
				String monitorTypeCode = (String) bean.get(QcExpdataRow.FIELD_Monitortypecode);
				String qcTypeCode = (String) bean.get(QcExpdataRow.FIELD_Qctypecode);

				if (QcHelper.isSampleFromSampling(qcTypeCode)) {
					List<GlobalParameter> parms = new ArrayList<>();
					parms.add(new GlobalParameter("sampleCode", sampleCode));
					String sql = "select t.monitortype from qc_sampledata t where t.samplenumber = @sampleCode";
					List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
					ValidUtils.notEmpty(rows, "无法索引对应的样品");
					ValidUtils.isTrue(monitorTypeCode.equals(rows.get(0).getSafeString("monitortype")), "监测类型和样品编号冲突");
				}
			}
		}
	}

	// 完善任务数据
	private List<RowBase> completeTaskDataDes(List<RowBase> taskList) throws Exception {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "select t.operation_task_code,\n"
				+ "       t.samplenumber,\n"
				+ "       max(t3.name) ||'  '|| wm_concat(to_char(t2.monitorparamname)) DES\n"
				+ "  from qc_sampledata t\n"
				+ "  left join qc_sampledetaildata t1\n"
				+ "    on t.samplenumber = t1.samplenumber\n"
				+ "   and t1.type = '1'\n"
				+ "  left join qc_monitorparam t2\n"
				+ "    on t2.monitorparamcode = t1.monitorparam\n"
				+ "   and t2.monitortypecode = t.monitortype\n"
				+ "   and t2.isfieldparam = '1'\n"
				+ "  left join BC_SITE_INFO t3\n"
				+ "    on t3.code = t.point\n"
				+ " group by t.operation_task_code, t.samplenumber";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		Map<String, RowBase> taskDataDesMap = new HashMap<>();
		for (RowBase rowBase : rows) {
			String taskCode = rowBase.getSafeString("operation_task_code");
			String sampleCode = rowBase.getSafeString("samplenumber");
			if (!taskDataDesMap.containsKey(taskCode)) {
				RowBase desRow = new RowBase();
				String des = rowBase.getSafeString("DES");
				desRow.put("des", des);
				desRow.put("name", sampleCode);
				taskDataDesMap.put(taskCode, desRow);
			} else {
				RowBase desRow = taskDataDesMap.get(taskCode);
				String previousSampleCode = (String) desRow.get("name");
				desRow.put("name", previousSampleCode + "," + sampleCode);
			}
		}

		for (RowBase rowBase : taskList) {
			String type = (String) rowBase.get("type");
			if ("1".equals(type)) {
				String taskCode = (String) rowBase.get("id");
				if (taskDataDesMap.containsKey(taskCode)) {
					RowBase dataRow = taskDataDesMap.get(taskCode);
					String name = (String) dataRow.get("name");
					String des = (String) dataRow.get("des");
					rowBase.put("name", name);
					rowBase.put("des", des);
				}
			}
		}
		return taskList;
	}

	// 根据质控类型获取实验次数（一次采样对应一个采样编号）
	public static int getLabCount(String qcTypeCode) throws Exception {
		ValidUtils.hasText(qcTypeCode, "质控类型编码不能为空");
		return QcHelper.getLabCount(qcTypeCode);
	}

	private String crateTaskCode(QcTaskParam taskParam) throws Exception {
		String parentTaskCode = taskParam.getParentTaskCode();
		String companyCode = taskParam.getCompanyCode();
		String jobId = QcControl.LAB.getJobId();
		List<GlobalParameter> parms = new ArrayList<>();
		parms.add(new GlobalParameter("parentTaskCode", parentTaskCode));
		parms.add(new GlobalParameter("suffix", parentTaskCode + "-"));
		parms.add(new GlobalParameter("companyCode", companyCode));
		parms.add(new GlobalParameter("jobId", jobId));
		String sql = "select min(t.ln) valid_Num\n"
				+ "  from (select level ln from dual connect by level < 1000) t\n"
				+ "  left join operation_task t1\n"
				+ "    on t1.job_id = @jobId\n"
				+ "   and t1.wwtp_id = @companyCode\n"
				+ "   and t1.parent_task_code = @parentTaskCode\n"
				+ "   and to_number(replace(t1.task_code, @suffix, '')) = t.ln\n"
				+ " where 1 = 1\n"
				+ "   and t1.guid is null";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		RowBase rowBase = rows.get(0);
		int maxNum = rowBase.getSafeInt("valid_num");
		ValidUtils.isTrue(maxNum <= 999, "任务数超上限");
		return parentTaskCode + "-" + String.format("%03d", maxNum);
	}
}
